<template>
  <div class="course-detail-container">
    <div class="page-header">
      <div class="header-left">
        <el-button icon="ArrowLeft" @click="goBack">返回</el-button>
        <h1>课程详情</h1>
      </div>
      <div class="header-right">
        <el-button @click="editCourse">编辑课程</el-button>
        <el-dropdown @command="handleCourseAction">
          <el-button type="primary">
            操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="publish" v-if="course.status === 'draft'">发布课程</el-dropdown-item>
              <el-dropdown-item command="unpublish" v-if="course.status === 'published'">下架课程</el-dropdown-item>
              <el-dropdown-item command="duplicate">复制课程</el-dropdown-item>
              <el-dropdown-item command="export">导出数据</el-dropdown-item>
              <el-dropdown-item command="delete" divided>删除课程</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <div class="course-content">
      <el-row :gutter="20">
        <!-- 课程基本信息 -->
        <el-col :span="16">
          <el-card title="基本信息">
            <div class="course-info">
              <div class="course-header">
                <img :src="course.cover || '/images/default-course.png'" class="course-cover" />
                <div class="course-basic">
                  <h2>{{ course.title }}</h2>
                  <p class="course-subtitle">{{ course.subtitle }}</p>
                  <div class="course-meta">
                    <el-tag :type="getStatusType(course.status)">
                      {{ getStatusText(course.status) }}
                    </el-tag>
                    <span class="instructor">讲师：{{ course.instructorName }}</span>
                    <span class="category">分类：{{ course.categoryName }}</span>
                  </div>
                </div>
              </div>
              
              <div class="course-description">
                <h3>课程描述</h3>
                <div v-html="course.description"></div>
              </div>
              
              <div class="course-objectives" v-if="course.objectives && course.objectives.length">
                <h3>学习目标</h3>
                <ul>
                  <li v-for="objective in course.objectives" :key="objective">
                    {{ objective }}
                  </li>
                </ul>
              </div>
            </div>
          </el-card>

          <!-- 课程章节 -->
          <el-card title="课程章节" style="margin-top: 20px">
            <div class="chapters-list">
              <div 
                v-for="(chapter, index) in chapters"
                :key="chapter.id"
                class="chapter-item"
              >
                <div class="chapter-header">
                  <div class="chapter-info">
                    <h4>第{{ index + 1 }}章 {{ chapter.title }}</h4>
                    <p>{{ chapter.description }}</p>
                  </div>
                  <div class="chapter-actions">
                    <el-button size="small" @click="editChapter(chapter)">编辑</el-button>
                    <el-button size="small" @click="addLesson(chapter)">添加课时</el-button>
                  </div>
                </div>
                
                <div class="lessons-list" v-if="chapter.lessons && chapter.lessons.length">
                  <div 
                    v-for="(lesson, lessonIndex) in chapter.lessons"
                    :key="lesson.id"
                    class="lesson-item"
                  >
                    <div class="lesson-info">
                      <span class="lesson-number">{{ lessonIndex + 1 }}</span>
                      <span class="lesson-title">{{ lesson.title }}</span>
                      <span class="lesson-duration">{{ lesson.duration }}分钟</span>
                      <el-tag size="small" :type="lesson.type === 'video' ? 'primary' : 'success'">
                        {{ lesson.type === 'video' ? '视频' : '文档' }}
                      </el-tag>
                    </div>
                    <div class="lesson-actions">
                      <el-button size="small" @click="previewLesson(lesson)">预览</el-button>
                      <el-button size="small" @click="editLesson(lesson)">编辑</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <el-button type="primary" @click="addChapter" style="margin-top: 16px">
              添加章节
            </el-button>
          </el-card>
        </el-col>

        <!-- 统计信息 -->
        <el-col :span="8">
          <el-card title="统计信息">
            <div class="stats-grid">
              <div class="stat-item">
                <div class="stat-number">{{ courseStats.studentCount || 0 }}</div>
                <div class="stat-label">学习人数</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ courseStats.completionRate || 0 }}%</div>
                <div class="stat-label">完成率</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ courseStats.averageRating || 0 }}</div>
                <div class="stat-label">平均评分</div>
              </div>
              <div class="stat-item">
                <div class="stat-number">{{ courseStats.totalDuration || 0 }}</div>
                <div class="stat-label">总时长(分钟)</div>
              </div>
            </div>
          </el-card>

          <!-- 课程设置 -->
          <el-card title="课程设置" style="margin-top: 20px">
            <div class="course-settings">
              <div class="setting-item">
                <span class="label">价格：</span>
                <span class="value">¥{{ course.price || 0 }}</span>
              </div>
              <div class="setting-item">
                <span class="label">难度等级：</span>
                <el-rate v-model="course.difficulty" disabled />
              </div>
              <div class="setting-item">
                <span class="label">是否免费：</span>
                <el-tag :type="course.isFree ? 'success' : 'warning'">
                  {{ course.isFree ? '免费' : '付费' }}
                </el-tag>
              </div>
              <div class="setting-item">
                <span class="label">创建时间：</span>
                <span class="value">{{ formatTime(course.createTime) }}</span>
              </div>
              <div class="setting-item">
                <span class="label">更新时间：</span>
                <span class="value">{{ formatTime(course.updateTime) }}</span>
              </div>
            </div>
          </el-card>

          <!-- 最近学员 -->
          <el-card title="最近学员" style="margin-top: 20px">
            <div class="recent-students">
              <div 
                v-for="student in recentStudents"
                :key="student.id"
                class="student-item"
                @click="viewStudent(student.id)"
              >
                <el-avatar :src="student.avatar" :size="32" />
                <div class="student-info">
                  <div class="student-name">{{ student.username }}</div>
                  <div class="student-progress">进度：{{ student.progress }}%</div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细数据标签页 -->
      <el-card style="margin-top: 20px">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane label="学员管理" name="students">
            <div class="students-table">
              <el-table :data="students" v-loading="loadingData">
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="realName" label="真实姓名" />
                <el-table-column prop="progress" label="学习进度" width="120">
                  <template #default="{ row }">
                    <el-progress :percentage="row.progress" :width="80" />
                  </template>
                </el-table-column>
                <el-table-column prop="lastStudyTime" label="最后学习" width="180">
                  <template #default="{ row }">
                    {{ formatTime(row.lastStudyTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="studyDuration" label="学习时长" width="120" />
                <el-table-column label="操作" width="150">
                  <template #default="{ row }">
                    <el-button size="small" @click="viewStudent(row.id)">查看</el-button>
                    <el-button size="small" @click="sendMessage(row.id)">消息</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="评价反馈" name="reviews">
            <div class="reviews-list">
              <div 
                v-for="review in reviews"
                :key="review.id"
                class="review-item"
              >
                <div class="review-header">
                  <el-avatar :src="review.userAvatar" :size="40" />
                  <div class="review-info">
                    <div class="reviewer-name">{{ review.username }}</div>
                    <el-rate v-model="review.rating" disabled size="small" />
                    <div class="review-time">{{ formatTime(review.createTime) }}</div>
                  </div>
                </div>
                <div class="review-content">{{ review.content }}</div>
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="数据分析" name="analytics">
            <div class="analytics-content">
              <el-row :gutter="20">
                <el-col :span="12">
                  <div class="chart-container">
                    <h4>学习进度分布</h4>
                    <!-- 这里可以集成图表组件 -->
                    <div class="chart-placeholder">图表区域</div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="chart-container">
                    <h4>学习时间趋势</h4>
                    <div class="chart-placeholder">图表区域</div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCourseDetail,
  getCourseChapters,
  getCourseStats,
  getCourseStudents,
  getCourseReviews,
  getRecentStudents,
  publishCourse,
  unpublishCourse,
  deleteCourse
} from '@/api/classroom'
import { formatTime } from '@/utils'

const route = useRoute()
const router = useRouter()

// 响应式数据
const course = ref({})
const chapters = ref([])
const courseStats = ref({})
const students = ref([])
const reviews = ref([])
const recentStudents = ref([])
const activeTab = ref('students')
const loadingData = ref(false)

// 页面加载
onMounted(async () => {
  await loadCourseDetail()
  await loadChapters()
  await loadCourseStats()
  await loadRecentStudents()
  await loadTabData()
})

// 加载课程详情
const loadCourseDetail = async () => {
  try {
    const response = await getCourseDetail(route.params.id)
    if (response.code === 200) {
      course.value = response.data
    }
  } catch (error) {
    console.error('获取课程详情失败:', error)
    ElMessage.error('获取课程详情失败')
  }
}

// 加载章节
const loadChapters = async () => {
  try {
    const response = await getCourseChapters(route.params.id)
    if (response.code === 200) {
      chapters.value = response.data || []
    }
  } catch (error) {
    console.error('获取章节失败:', error)
  }
}

// 加载统计数据
const loadCourseStats = async () => {
  try {
    const response = await getCourseStats(route.params.id)
    if (response.code === 200) {
      courseStats.value = response.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 加载最近学员
const loadRecentStudents = async () => {
  try {
    const response = await getRecentStudents(route.params.id)
    if (response.code === 200) {
      recentStudents.value = response.data || []
    }
  } catch (error) {
    console.error('获取最近学员失败:', error)
  }
}

// 加载标签页数据
const loadTabData = async () => {
  loadingData.value = true
  try {
    switch (activeTab.value) {
      case 'students':
        const studentsResponse = await getCourseStudents(route.params.id)
        if (studentsResponse.code === 200) {
          students.value = studentsResponse.data || []
        }
        break
      case 'reviews':
        const reviewsResponse = await getCourseReviews(route.params.id)
        if (reviewsResponse.code === 200) {
          reviews.value = reviewsResponse.data || []
        }
        break
      case 'analytics':
        // 加载分析数据
        break
    }
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loadingData.value = false
  }
}

// 标签页切换
const handleTabChange = (tab) => {
  activeTab.value = tab
  loadTabData()
}

// 课程操作处理
const handleCourseAction = async (command) => {
  switch (command) {
    case 'publish':
      await publishCourseAction()
      break
    case 'unpublish':
      await unpublishCourseAction()
      break
    case 'duplicate':
      duplicateCourse()
      break
    case 'export':
      exportCourseData()
      break
    case 'delete':
      await deleteCourseAction()
      break
  }
}

// 发布课程
const publishCourseAction = async () => {
  try {
    await publishCourse(course.value.id)
    course.value.status = 'published'
    ElMessage.success('课程发布成功')
  } catch (error) {
    console.error('发布课程失败:', error)
    ElMessage.error('发布课程失败')
  }
}

// 下架课程
const unpublishCourseAction = async () => {
  try {
    await unpublishCourse(course.value.id)
    course.value.status = 'draft'
    ElMessage.success('课程下架成功')
  } catch (error) {
    console.error('下架课程失败:', error)
    ElMessage.error('下架课程失败')
  }
}

// 删除课程
const deleteCourseAction = async () => {
  try {
    await ElMessageBox.confirm('确认要删除此课程吗？此操作不可逆！', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteCourse(course.value.id)
    ElMessage.success('课程删除成功')
    router.push('/classroom/course')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除课程失败')
    }
  }
}

// 编辑课程
const editCourse = () => {
  router.push(`/classroom/course/edit/${course.value.id}`)
}

// 查看学员
const viewStudent = (studentId) => {
  router.push(`/user/detail/${studentId}`)
}

// 发送消息
const sendMessage = (userId) => {
  router.push(`/message/send?userId=${userId}`)
}

// 添加章节
const addChapter = () => {
  router.push(`/classroom/course/${course.value.id}/chapter/create`)
}

// 编辑章节
const editChapter = (chapter) => {
  router.push(`/classroom/chapter/edit/${chapter.id}`)
}

// 添加课时
const addLesson = (chapter) => {
  router.push(`/classroom/chapter/${chapter.id}/lesson/create`)
}

// 编辑课时
const editLesson = (lesson) => {
  router.push(`/classroom/lesson/edit/${lesson.id}`)
}

// 预览课时
const previewLesson = (lesson) => {
  router.push(`/classroom/lesson/preview/${lesson.id}`)
}

// 复制课程
const duplicateCourse = () => {
  router.push(`/classroom/course/duplicate/${course.value.id}`)
}

// 导出数据
const exportCourseData = () => {
  ElMessage.info('导出功能开发中...')
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'published': 'success',
    'draft': 'warning',
    'archived': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'published': '已发布',
    'draft': '草稿',
    'archived': '已归档'
  }
  return textMap[status] || '未知'
}

// 返回
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.course-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
    
    h1 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .header-right {
    display: flex;
    gap: 12px;
  }
}

.course-info {
  .course-header {
    display: flex;
    gap: 20px;
    margin-bottom: 24px;
    
    .course-cover {
      width: 200px;
      height: 120px;
      object-fit: cover;
      border-radius: 8px;
    }
    
    .course-basic {
      flex: 1;
      
      h2 {
        margin: 0 0 8px 0;
        font-size: 20px;
        color: #303133;
      }
      
      .course-subtitle {
        margin: 0 0 16px 0;
        color: #606266;
      }
      
      .course-meta {
        display: flex;
        gap: 16px;
        align-items: center;
        flex-wrap: wrap;
        
        span {
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
  
  .course-description,
  .course-objectives {
    margin-bottom: 24px;
    
    h3 {
      margin: 0 0 12px 0;
      font-size: 16px;
      color: #303133;
    }
    
    ul {
      margin: 0;
      padding-left: 20px;
      
      li {
        margin-bottom: 8px;
        color: #606266;
      }
    }
  }
}

.chapters-list {
  .chapter-item {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    margin-bottom: 16px;
    overflow: hidden;
    
    .chapter-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 16px;
      background-color: #f8f9fa;
      
      .chapter-info {
        flex: 1;
        
        h4 {
          margin: 0 0 8px 0;
          color: #303133;
        }
        
        p {
          margin: 0;
          color: #606266;
          font-size: 14px;
        }
      }
      
      .chapter-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .lessons-list {
      .lesson-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 16px;
        border-top: 1px solid #e4e7ed;
        
        .lesson-info {
          display: flex;
          align-items: center;
          gap: 12px;
          
          .lesson-number {
            width: 24px;
            height: 24px;
            background-color: #409eff;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
          }
          
          .lesson-title {
            font-weight: 500;
            color: #303133;
          }
          
          .lesson-duration {
            color: #909399;
            font-size: 12px;
          }
        }
        
        .lesson-actions {
          display: flex;
          gap: 8px;
        }
      }
    }
  }
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  
  .stat-item {
    text-align: center;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    
    .stat-number {
      font-size: 20px;
      font-weight: 600;
      color: #409eff;
      margin-bottom: 8px;
    }
    
    .stat-label {
      color: #606266;
      font-size: 12px;
    }
  }
}

.course-settings {
  .setting-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    
    .label {
      color: #606266;
      font-size: 14px;
    }
    
    .value {
      color: #303133;
      font-size: 14px;
    }
  }
}

.recent-students {
  .student-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 0;
    cursor: pointer;
    
    &:hover {
      background-color: #f8f9fa;
    }
    
    .student-info {
      flex: 1;
      
      .student-name {
        font-weight: 500;
        color: #303133;
        margin-bottom: 4px;
      }
      
      .student-progress {
        color: #606266;
        font-size: 12px;
      }
    }
  }
}

.reviews-list {
  .review-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    .review-header {
      display: flex;
      gap: 12px;
      margin-bottom: 12px;
      
      .review-info {
        .reviewer-name {
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
        }
        
        .review-time {
          color: #909399;
          font-size: 12px;
          margin-top: 4px;
        }
      }
    }
    
    .review-content {
      color: #606266;
      line-height: 1.5;
    }
  }
}

.chart-container {
  h4 {
    margin: 0 0 16px 0;
    color: #303133;
  }
  
  .chart-placeholder {
    height: 200px;
    background-color: #f8f9fa;
    border: 1px dashed #e4e7ed;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    
    .header-left {
      width: 100%;
      justify-content: space-between;
    }
  }
  
  .course-header {
    flex-direction: column;
    
    .course-cover {
      width: 100%;
      height: 200px;
    }
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .chapter-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .lesson-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>
